import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.File;
import java.io.IOException;

public class BaiDuPic {
    public static void main(String[] args) throws IOException {
        int size=0;
        int x = 0x0001e;
        //模拟发送三次请求
        for(int j=0;j<4;j++) {
            Connection.Response connection;
            connection = Jsoup.connect("http://image.baidu.com/search/avatarjson?tn=resultjsonavatarnew&ie=utf-8&word=%E5%A3%81%E7%BA%B8&cg=wallpaper&pn=90&rn=30&itg=0&z=0&fr=&width=&height=&lm=-1&ic=0&s=0&st=-1&gsm=6000" + Integer.toHexString(x)).execute();
            //将得到的字符串转换为JSON类型
            JSONObject jsonObject = JSONObject.parseObject(connection.body());
            //得到所有的img
            JSONArray jsonArray = JSONObject.parseArray(jsonObject.get("imgs").toString());
            for (int i = 0; i < jsonArray.size(); i++) {
                //得到图片的URL
                String url = JSONObject.parseObject(jsonArray.get(i).toString()).get("objURL").toString();
                //新建一个连接，用来下载URL上的图片
                Connection.Response connection2;
                try {
                    //此处忽略了返回类型，加入了userAgent是因为有些网站不让爬虫访问，加入后一部分网站就可以访问了
                    connection2 = Jsoup.connect(url).ignoreContentType(true).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36").execute();
                }catch (Exception e){
                    e.printStackTrace();
                    continue;
                }
                File file = new File("D:\\dvp\\workspace\\pic\\"+size+".jpg");
                //将图片写入到本地计算机，此处使用了apache common io，非必须，只是可以少些很多io代码
                FileUtils.writeByteArrayToFile(file,connection2.bodyAsBytes());
                size++;
            }
            x = x + 18;
        }
    }
}
